package com.superarai.portal.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.util.TokenProcessor;
import org.seasar.struts.annotation.ActionForm;
import org.seasar.struts.annotation.Execute;

import com.superarai.portal.annotation.LoginCheck;
import com.superarai.portal.dto.LoginInfoDto;
import com.superarai.portal.entity.UserInfo;
import com.superarai.portal.enums.Config;
import com.superarai.portal.form.SignupForm;
import com.superarai.portal.service.AbstractUserInfoService;
import com.superarai.portal.util.Assertion;

public class SignupAction {
	@ActionForm
	@Resource
	public SignupForm signupForm;
	
	@Resource
	protected AbstractUserInfoService userInfoService;
	
	@Resource
	protected HttpServletRequest request;
	
	@Resource
	protected LoginInfoDto loginInfoDto;
	
	private static final String SIGNUP_URL = Config.Page.SIGNUP.getURL();
	
	/**
	 * ユーザ登録 初期表示
	 * @return signup.jsp
	 */
	@Execute(validator = false)
	public String index() {
		TokenProcessor.getInstance().saveToken(request);
		return "signup.jsp";
	}
	
	/**
	 * ユーザ登録 実行
	 * 
	 * 成功時<br />
	 * @return ユーザ登録完了画面<br />
	 * <br />
	 * 失敗<br />
	 * @return ユーザ登録ページ<br />
	 */
	@Execute(validator = true, input = "/signup?redirect=true", redirect = true)
	public String doSignup() {
		Assertion.notNull(signupForm.userId);
		Assertion.notNull(signupForm.password1);
		Assertion.notNull(signupForm.password2);

		if(!TokenProcessor.getInstance().isTokenValid(request,true))
			return SIGNUP_URL;
		
		if(isExistsUserId(signupForm.userId)) 
			return SIGNUP_URL; 
		
		createUser(signupForm.userId, signupForm.password1);
		login(signupForm.userId);

		return "/signup/complete";
	}
	
	@LoginCheck
	@Execute(validator = false)
	public String complete() {
		return "complete.jsp";
	}
	
	private boolean isExistsUserId(String userId) {
		UserInfo user = userInfoService.findById(userId);
		return user == null ? false : true;
	}
	
	private void createUser(String userId, String password) {
		UserInfo user = new UserInfo();
		user.userId = userId;
		user.password = password;
		userInfoService.insert(user);
	}
	
	private void login(String userId) {
		loginInfoDto.userId = userId;
		loginInfoDto.loginSuccess();
	}
}
